package com.whub507.msgmanager.sso.client.sso;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;

import javax.net.ssl.*;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * 重写openConnection，支持https
 * 
 * @author wcl
 *
 */
public class SimpleClientHttpRequestFactory4Https extends SimpleClientHttpRequestFactory {

	private static Logger logger = LoggerFactory.getLogger(SimpleClientHttpRequestFactory4Https.class);

	/**
	 * * 覆盖java默认的证书验证
	 */
	private final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
		public X509Certificate[] getAcceptedIssuers() {
			return new X509Certificate[] {};
		}

		public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		}

		public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		}
	} };

	/**
	 * 设置不验证主机
	 */
	private final HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
		public boolean verify(String hostname, SSLSession session) {
			return true;
		}
	};

	@Override
	protected HttpURLConnection openConnection(URL url, Proxy proxy) throws IOException {
		URLConnection urlConnection = (proxy != null ? url.openConnection(proxy) : url.openConnection());
		if (!HttpURLConnection.class.isInstance(urlConnection)) {
			throw new IllegalStateException("HttpURLConnection required for [" + url + "] but got: " + urlConnection);
		}

		if ("https".equalsIgnoreCase(url.getProtocol())) {
			HttpsURLConnection conn = (HttpsURLConnection) urlConnection;
			SSLContext sc;
			try {
				sc = SSLContext.getInstance("TLS");
				sc.init(null, trustAllCerts, new java.security.SecureRandom());
				SSLSocketFactory newFactory = sc.getSocketFactory();
				conn.setSSLSocketFactory(newFactory);
				conn.setHostnameVerifier(DO_NOT_VERIFY);
				return conn;
			} catch (NoSuchAlgorithmException | KeyManagementException e) {
				logger.error("SimpleClientHttpRequestFactory4Https openConnection failed.", e);
			}

		}

		return (HttpURLConnection) urlConnection;
	}

}
